import javafx.concurrent.WorkerStateEvent;

import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;

class Worker extends Thread{
    // 线程池这里的worker代表的含义和之前阻塞队列中的worker差别很大
    private LinkedBlockingQueue<Runnable> queue = null;
    public Worker(LinkedBlockingQueue<Runnable> queue){
        super("worker");
        this.queue = queue;
    }

    public void run(){
        // try 必须放在while外头，
        try{
            while(!Thread.interrupted()){
                Runnable runnable = queue.take();
                runnable.run();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
            System.out.println("线程收到一个notify");
        }
    }

}

public class MyThreadPool {
    private int maxWorkerCount = 10;
    private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    private LinkedList<Worker> workerList = new LinkedList<>();
//    public MyThreadPool(){
//        // 先将线程船舰处理啊
//    }

    public void submit(Runnable command) throws InterruptedException {
        // 这里没没有采取一次性就将全部宣称创建出来的做法，而是渐进的，这样分流，提高了用户体验
        if (workerList.size() < maxWorkerCount) {
              // 当前 worker 数不足, 就继续创建 worker
              Worker worker = new Worker(queue);
              worker.start();
              synchronized (workerList){
                  workerList.add(worker);
              }
        }
            // 将任务添加到任务队列中
        synchronized (queue){
            queue.put(command);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool();
        myThreadPool.submit(new Runnable(){
            public void run(){
                System.out.println("吃饭");
            }
        });
        Thread.sleep(1000);

    }


}
